package com.chianghao.rock.system.service.user_role;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chianghao.core.frame.service.BaseService;
import com.chianghao.core.mybatis.sql.SqlWrapper;
import com.chianghao.core.mybatis.sql.db_enum.SqlOperators;
import com.chianghao.rock.system.dao.role.RoleMapper;
import com.chianghao.rock.system.dao.user_role.UserRoleMapper;
import com.chianghao.rock.system.entity.Role;
import com.chianghao.rock.system.entity.UserRole;

@Service
public class UserRoleService extends BaseService<UserRoleMapper, UserRole> {

	@Autowired
	RoleMapper roleMapper;
	
	/**
	 * 绑定用户和角色的关系
	 * 先删除后绑定
	 * @param userId
	 * @param roleIds
	 */
	public void doSaveRelation(Long userId, List<Long> roleIds) {
		//删除绑定关系
		UserRole where = new UserRole();
		where.setUserId(userId);
		this.mapper.deleteByEntity(where);
		
		List<UserRole> list =new ArrayList<UserRole>();
		//添加绑定关系
		for(Long roleId:roleIds) {
			UserRole item = new UserRole();
			item.setRoleId(roleId);
			item.setUserId(userId);
			list.add(item);
		}
		this.mapper.batchInsert(list);
	}

	/**
	 * 查询用户的角色
	 * @param userId
	 * @return
	 */
	public List<Role> queryByUserId(Long userId) {
		UserRole where = new UserRole();
		where.setUserId(userId);
		List<UserRole> list  = this.mapper.queryListByEntity(where, null);
		List<Long> ids = list.stream().map(item->item.getRoleId()).collect(Collectors.toList());
		Long[] idsArray = ids.toArray(new Long[ids.size()]);
		return this.roleMapper.queryList(new SqlWrapper().addCondition(Role::getId,SqlOperators.in,idsArray));
	}




}